from attr.setters import validate
from tornado.web import RequestHandler
from tornado.httpclient import HTTPClient,HTTPRequest,HTTPResponse,AsyncHTTPClient

class DownloadHandler(RequestHandler):
    def get(self):
        url = self.get_query_argument('url')
        filename = self.get_query_argument('filename','momo.html')
        #发起异步请求
        Client = AsyncHTTPClient()
        response:HTTPResponse =  Client.fetch(url,validate_cert=False)
        # print(response.body)
        from app import os,BASE_DIR
        dir = os.path.join(BASE_DIR,'static/downloads')
        with  open (os.path.join(dir,filename),'wb') as f:
            f.write(response.body)

        self.write('下载成功')


class AsyncDownloadHandler(RequestHandler):
    async def get(self):
        from app import os, BASE_DIR
        url = self.get_query_argument('url')
        filename = self.get_query_argument('filename', 'momo1.html')

        download_dir = os.path.join(BASE_DIR, 'static', 'downloads')
        os.makedirs(download_dir, exist_ok=True)

        client = AsyncHTTPClient()
        resp: HTTPResponse = await client.fetch(url, validate_cert=False)

        filepath = os.path.join(download_dir, filename)
        with open(filepath, 'wb') as f:
            f.write(resp.body)

        print(resp.effective_url, '下载成功')
        self.write('下载完成并保存成功!')
        # 可选：显式结束
        self.finish()